package com.lin.realm;

import com.lin.entity.AclPermission;
import com.lin.entity.AclRole;
import com.lin.service.AclUserService;
import com.lin.shiro.JWTToken;
import com.lin.utils.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 霖霖
 * @version 1.0
 * @date 2023/3/29 9:54
 * @Description 管理员
 */
@Component
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    private AclUserService aclUserService;
    /**
     * 限定这个realm只能处理JWTToken
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String adminId = (String) principalCollection.getPrimaryPrincipal();

        List<AclRole> rolesEntity = aclUserService.getRoles(adminId);
        List<String> roles = rolesEntity.stream().map(AclRole::getRoleValue).collect(Collectors.toList());
        List<String> roleIds = rolesEntity.stream().map(AclRole::getId).collect(Collectors.toList());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roles);
        if (roleIds.size() == 0)
            return simpleAuthorizationInfo;
        List<AclPermission> permissionsEntity = aclUserService.getPermissions(roleIds);
        List<String> permissions = permissionsEntity.stream().map(AclPermission::getPermissionValue).collect(Collectors.toList());

        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String token = (String) authenticationToken.getCredentials();
        if (!JWTUtil.checkToken(token)){
            throw new AuthenticationException("token校验失败,请重新登录");
        }
        String adminId = JWTUtil.getTokenInfo(token);

        return new SimpleAuthenticationInfo(adminId,token,this.getName());
    }
}
